<?php
/**
 * CpController
 * 
 * @author
 * @version 
 */
require_once 'Zend/Controller/Action.php';
class Admin_PageController extends Sunnet_Controller_Action
{
	var $_arrParam;
	public function init()
    {
//    	Truyền các tham số nhận được ra view
    	$this->_arrParam = $this->_request->getParams();
    	$this->view->arrParam = $this->_arrParam;
    	if (empty($this->_arrParam['page'])) {
    		$this->_arrParam['page'] = 1;
    	}
    	if (empty($this->_arrParam['line_per_page'])) {
    		$this->_arrParam['line_per_page'] = 10;
    	}
        Zend_Loader::loadClass('Admin_Models_MenuModel');
         $db = new Admin_Models_MenuModel();
         $mainmenu = $db->loadmainmenu();
         $this->view->mainmenu = $mainmenu; 
         
         function vn_str_filter ($str){
			$unicode = array(
					'a'=>'á|à|ả|ã|ạ|ă|ắ|ặ|ằ|ẳ|ẵ|â|ấ|ầ|ẩ|ẫ|ậ',
					'd'=>'đ',
					'e'=>'é|è|ẻ|ẽ|ẹ|ê|ế|ề|ể|ễ|ệ',
					'i'=>'í|ì|ỉ|ĩ|ị',
					'o'=>'ó|ò|ỏ|õ|ọ|ô|ố|ồ|ổ|ỗ|ộ|ơ|ớ|ờ|ở|ỡ|ợ',
					'u'=>'ú|ù|ủ|ũ|ụ|ư|ứ|ừ|ử|ữ|ự',
					'y'=>'ý|ỳ|ỷ|ỹ|ỵ',
					'A'=>'Á|À|Ả|Ã|Ạ|Ă|Ắ|Ặ|Ằ|Ẳ|Ẵ|Â|Ấ|Ầ|Ẩ|Ẫ|Ậ',
					'D'=>'Đ',
					'E'=>'É|È|Ẻ|Ẽ|Ẹ|Ê|Ế|Ề|Ể|Ễ|Ệ',
					'I'=>'Í|Ì|Ỉ|Ĩ|Ị',
					'O'=>'Ó|Ò|Ỏ|Õ|Ọ|Ô|Ố|Ồ|Ổ|Ỗ|Ộ|Ơ|Ớ|Ờ|Ở|Ỡ|Ợ',
					'U'=>'Ú|Ù|Ủ|Ũ|Ụ|Ư|Ứ|Ừ|Ử|Ữ|Ự',
					'Y'=>'Ý|Ỳ|Ỷ|Ỹ|Ỵ',
					'_'=>' ',
			);
		
			foreach($unicode as $nonUnicode=>$uni){
				$str = preg_replace("/($uni)/i", $nonUnicode, $str);
			}
			return $str;
		}
    }

    public function preDispatch(){
        $this->view->headScript()->appendFile('/js/ckeditor/ckeditor.js','text/javascript');
         $template_path = TEMPLATE_PATH . "/admin/default/";
		$this->loadTemplate($template_path,'template.ini','template');           
    	$auth = Zend_Auth::getInstance();
        $this->view->userName = $auth->getIdentity()->username;
    	if ((!$auth->hasIdentity() || !$auth->getIdentity()->admin) && ($this->_arrParam['action'] != 'login')) {
    		$this->_forward('login','index','admin',array('action'	=> 'login'));//,$this->_arrParam);
    	}
        $this->view->headScript()->appendFile('/js/ckeditor/ckeditor.js','text/javascript');
        $this->view->headScript()->appendFile('/js/ckeditor/styles.js','text/javascript');
        $this->view->headScript()->appendFile('/js/ckeditor/ckeditor.css','text/css');
    }
   
    public function indexAction(){
         Zend_loader::loadClass('Admin_Models_PageModel');
//		Load các model và form sử dụng trong action
         $db = new Admin_Models_PageModel();
         $listpage = $db->listpage();
         $currentPage = 1;		 
		$i = $this->_getParam('page',1);
		if(!empty($i))
		{
			$currentPage = $i;
		}
		$paginator = Zend_Paginator::factory($listpage);
		$paginator->setItemCountPerPage(10)
		->setPageRange(4)
		->setCurrentPageNumber($currentPage);
		$this->view->paginator = $paginator;                 
    }

    public function addPageAction(){
        Zend_loader::loadClass('Admin_Forms_AddPageForm');
        Zend_loader::loadClass('Admin_Models_PageModel');
		$session = new Zend_Session_Namespace();

        $form = new Admin_Forms_AddPageForm(null);
        
		$this->view->form = $form;
       		$request=$this->getRequest();
				
		if($request->isPost()){
			//lay title alias theo title
				$filename = $this->_request->getParam('name');
				$filename_cut = vn_str_filter(trim($filename));

				try {
				$validator= $this->_request->getParams();
				
					if(is_array($form->avatar->getFileName(null,false))== false){
						$info = pathinfo($form->avatar->getFileName(null,false));
						
						$ext = $info['extension']?".".$info['extension']:"";
						//filter for renaming.. prepend with current time
						$form->avatar->addFilter(new Zend_Filter_File_Rename(array(
								"target"=>$filename_cut.'_'.time().$ext,
								"overwrite"=>true)));
						$form->getValue('avatar');
						$imgpath= '/imagesnote/note/'.$filename_cut.'_'.time().$ext;
						$image = UPLOAD_PATH.'/imagesnote/note/'.$filename_cut.'_'.time().$ext;
										
						$thumb = new WJG_Resource_Thumbnail($image,90,90);
									   $name_320 = pathinfo($thumb->img_320);
									   $name_480 = pathinfo($thumb->img_480);
									   $name_800 = pathinfo($thumb->img_800);
								   
						$image_320 = '/imagesnote/thumb_note/'.$name_320['filename'].$ext;
										$image_480 = '/imagesnote/medium_note/'.$name_480['filename'].$ext;
										$image_800 = '/imagesnote/note/'.$name_800['filename'].$ext;
					}else{
						$imgpath= null;
						$image_320 = null;
											$image_480 = null;
											$image_800 = null;
					}
					if ($form->isValid($validator)==FALSE){
							$this->view->messagesError = $form->getMessagesError();
					}else {
						

											//neu la Chap mot truyen thi lay hinh dai dien cua truyen do
											$db= new Admin_Models_PageModel();
											
											$data= array(
													'UserID'=>  $session->userid,
													'title_alias' => $filename_cut,
													'content'=>$this->_request->getParam('content'),

													'link_images_thumb'=>$image_320,
													'link_images_medium'=>$image_480,
													'link_images'=>$image_800,    
													
													'name'=>$this->_request->getParam('name'),
													'description'=>$this->_request->getParam('description'),												
													'link_url'=>$this->_request->getParam('link_url'), //de dat link ra ngoai anh
													
													'seo_title'=>$this->_request->getParam('seo_title'),
													'seo_keywords'=>$this->_request->getParam('seo_keywords'),
													'seo_description'=>$this->_request->getParam('seo_description'),
											);
											try{
												$result = $db->addPage($data);

											}catch(Exception $e)
											{
												echo $e;
											}

										if($result>0)
										{
											//<script>alert('Page added');
											echo "<script>window.location = '/admin/page/';</script>";
											
										}else {
											echo "<script>alert('Add page Fail');window.location = '/admin/page/';</script>";
										}					
					}

				} catch (Exception $e) {
					echo $e;
				}
		}
	
    }

    public function editPageAction(){

         $id = $this->_request->getParam('id');

        if(intval($id)>0){ 

	        Zend_loader::loadClass('Admin_Forms_AddPageForm');
	        Zend_loader::loadClass('Admin_Models_PageModel');
			$session = new Zend_Session_Namespace();

	        $form = new Admin_Forms_AddPageForm(null);

			$db = new Admin_Models_PageModel();
	        $result_edit = $db->loadpagebyid($id);

	        $form->setDefaults($result_edit); 
			        
	        $this->view->form=$form;
			$this->view->data = $result_edit;

	        $request=$this->getRequest();
	        if($request->isPost()){
				//lay title alias
					$filename = $this->_request->getParam('name');
					$filename_cut = vn_str_filter(trim($filename));

					try {
						$validator= $this->_request->getParams();
						if(is_array($form->avatar->getFileName(null,false))== false){
						$info = pathinfo($form->avatar->getFileName(null,false));
						
						$ext = $info['extension']?".".$info['extension']:"";
			 			//filter for renaming.. prepend with current time
						$form->avatar->addFilter(new Zend_Filter_File_Rename(array(
								"target"=>$filename_cut.'_'.time().$ext,
								"overwrite"=>true)));
						$form->getValue('avatar');
						$imgpath= '/imagesnote/note/'.$filename_cut.'_'.time().$ext;
						$image = UPLOAD_PATH.'/imagesnote/note/'.$filename_cut.'_'.time().$ext;
						$thumb = new WJG_Resource_Thumbnail($image,90,90);
						 $name_320 = pathinfo($thumb->img_320);
		                               $name_480 = pathinfo($thumb->img_480);
		                               $name_800 = pathinfo($thumb->img_800);
		                           
						$image_320 = '/imagesnote/thumb_note/'.$name_320['filename'].$ext;
		                                $image_480 = '/imagesnote/medium_note/'.$name_480['filename'].$ext;
		                                $image_800 = '/imagesnote/note/'.$name_800['filename'].$ext;
						}else{
							$imgpath= null;
							$image_320 = null;
		                                        $image_480 = null;
		                                        $image_800 = null;
						}
						if ($form->isValid($validator)==FALSE){
								$this->view->messagesError = $form->getMessagesError();
						}else {
		                           	//insert note lay UserActivity
		                            if($imgpath!= null){

										$data= array(
											'UserID'=>  $session->userid,
											'title_alias' => $filename_cut,
											'content'=>$this->_request->getParam('content'),
											'link_images_thumb'=>$image_320,
											'link_images_medium'=>$image_480,
											'link_images'=>$image_800,    
											'name'=>$this->_request->getParam('name'),
											'description'=>$this->_request->getParam('description'),												
											'link_url'=>$this->_request->getParam('link_url'), //de dat link ra ngoai anh

											'seo_title'=>$this->_request->getParam('seo_title'),
											'seo_keywords'=>$this->_request->getParam('seo_keywords'),
											'seo_description'=>$this->_request->getParam('seo_description'),
										);
									} else {
		                                    $data= array(
												'UserID'=>  $session->userid,
												'title_alias' => $filename_cut,
												'content'=>$this->_request->getParam('content'),	
												'name'=>$this->_request->getParam('name'),
												'description'=>$this->_request->getParam('description'),												
												'link_url'=>$this->_request->getParam('link_url'), //de dat link ra ngoai anh

												'seo_title'=>$this->_request->getParam('seo_title'),
												'seo_keywords'=>$this->_request->getParam('seo_keywords'),
												'seo_description'=>$this->_request->getParam('seo_description'),
		                                    );  
		                            }

							try{
		                        $result = $db->updatepage($data,$id);        
		                                             
		                    }catch(Exception $e){
								echo $e;
							}

							if($result>0){
								// <script>alert('Page added');
								echo "<script>window.location = '/admin/page/';</script>";		   				
							}else {
								echo "<script>alert('Add page Fail');window.location = '/admin/page/';</script>";
							}
							
						}
									
					} catch (Exception $e) {
						echo $e;
					}				
			} //end post edit
		} // neu ton tai id
    }
    
    public function delPageAction(){

       $id = $this->_request->getParam('id');
       Zend_loader::loadclass('Admin_Models_PageModel');

       $db_del = new Admin_Models_PageModel();      
       $result = $db_del->delpage($id);
       
       if($result>0){          
       		//alert('Xóa bài viết thành công ');  
			echo "<script>window.location = '/admin/page';</script>";
		}else {		
			echo "<script>alert('Xóa bài viết thất bại');window.location = '/admin/page';</script>";
		}
    }
	
}
